/**
 * 时间戳转换工具的JavaScript逻辑
 */

document.addEventListener('DOMContentLoaded', function() {
    // 初始化Feather图标
    feather.replace();
    
    // 获取DOM元素
    const currentTimestampEl = document.getElementById('current-timestamp');
    const timestampUnitEl = document.getElementById('timestamp-unit');
    const toggleUnitBtn = document.getElementById('toggle-unit');
    const copyTimestampBtn = document.getElementById('copy-timestamp');
    const toggleUpdateBtn = document.getElementById('toggle-update');
    
    // 时间戳转日期相关元素
    const inputTimestampEl = document.getElementById('input-timestamp');
    const timestampTypeEl = document.getElementById('timestamp-type');
    const timestampTimezoneEl = document.getElementById('timestamp-timezone');
    const convertToDateBtn = document.getElementById('convert-to-date');
    const dateValueEl = document.getElementById('date-value');
    
    // 日期转时间戳相关元素
    const inputDatetimeEl = document.getElementById('input-datetime');
    const dateTimezoneEl = document.getElementById('date-timezone');
    const outputTypeEl = document.getElementById('output-type');
    const convertToTimestampBtn = document.getElementById('convert-to-timestamp');
    const timestampValueSEl = document.getElementById('timestamp-value-s');
    const timestampValueMsEl = document.getElementById('timestamp-value-ms');
    
    // 状态变量
    let isMilliseconds = false; // 默认显示秒
    let isUpdating = true; // 默认自动更新
    let updateInterval; // 更新定时器
    
    // 更新当前时间戳的函数
    function updateCurrentTimestamp() {
        const now = new Date();
        const timestamp = isMilliseconds ? now.getTime() : Math.floor(now.getTime() / 1000);
        currentTimestampEl.textContent = timestamp;
    }
    
    // 开始自动更新时间戳
    function startUpdating() {
        updateCurrentTimestamp(); // 立即更新一次
        updateInterval = setInterval(updateCurrentTimestamp, 1000); // 每秒更新一次
        isUpdating = true;
        // 从DOM中获取翻译文本
        const pauseText = document.getElementById('pause-text') ? document.getElementById('pause-text').value : '暂停';
        toggleUpdateBtn.innerHTML = `<i data-feather="pause" class="me-1" style="width: 16px; height: 16px;"></i>${pauseText}`;
        feather.replace();
    }
    
    // 停止自动更新时间戳
    function stopUpdating() {
        clearInterval(updateInterval);
        isUpdating = false;
        // 从DOM中获取翻译文本
        const resumeText = document.getElementById('resume-text') ? document.getElementById('resume-text').value : '继续';
        toggleUpdateBtn.innerHTML = `<i data-feather="play" class="me-1" style="width: 16px; height: 16px;"></i>${resumeText}`;
        feather.replace();
    }
    
    // 初始化当前时间戳显示
    startUpdating();
    
    // 切换时间戳单位（秒/毫秒）
    toggleUnitBtn.addEventListener('click', function() {
        isMilliseconds = !isMilliseconds;
        // 从DOM中获取翻译文本
        const secondsText = document.getElementById('seconds-text') ? document.getElementById('seconds-text').value : '秒';
        const millisecondsText = document.getElementById('milliseconds-text') ? document.getElementById('milliseconds-text').value : '毫秒';
        timestampUnitEl.textContent = isMilliseconds ? millisecondsText : secondsText;
        updateCurrentTimestamp();
    });
    
    // 复制当前时间戳
    copyTimestampBtn.addEventListener('click', function() {
        const textToCopy = currentTimestampEl.textContent;
        navigator.clipboard.writeText(textToCopy).then(function() {
            // 复制成功，可以添加一些视觉反馈
            const originalText = copyTimestampBtn.innerHTML;
            // 使用通用的已复制文本
            copyTimestampBtn.innerHTML = '<i data-feather="check" class="me-1" style="width: 16px; height: 16px;"></i>✓';
            feather.replace();
            
            setTimeout(function() {
                copyTimestampBtn.innerHTML = originalText;
                feather.replace();
            }, 2000);
        });
    });
    
    // 切换时间戳更新状态（开始/暂停）
    toggleUpdateBtn.addEventListener('click', function() {
        if (isUpdating) {
            stopUpdating();
        } else {
            startUpdating();
        }
    });
    
    // 时间戳转日期时间
    convertToDateBtn.addEventListener('click', function() {
        const inputTimestamp = inputTimestampEl.value.trim();
        if (!inputTimestamp) {
            // 从DOM中获取错误提示文本，如果没有则使用默认值
            const errorText = document.getElementById('error-invalid-timestamp') ? 
                document.getElementById('error-invalid-timestamp').value : '请输入有效的时间戳';
            dateValueEl.textContent = errorText;
            return;
        }
        
        const timestampType = timestampTypeEl.value;
        const timezone = timestampTimezoneEl.value;
        
        let timestamp = parseInt(inputTimestamp, 10);
        if (isNaN(timestamp)) {
            dateValueEl.textContent = '请输入有效的数字';
            return;
        }
        
        // 如果是秒，转换为毫秒
        if (timestampType === 's') {
            timestamp *= 1000;
        }
        
        try {
            const date = moment(timestamp);
            const formattedDate = date.tz(timezone).format('YYYY-MM-DD HH:mm:ss z');
            dateValueEl.textContent = formattedDate;
        } catch (error) {
            dateValueEl.textContent = '转换失败，请检查输入';
        }
    });
    
    // 日期时间转时间戳
    convertToTimestampBtn.addEventListener('click', function() {
        const inputDatetime = inputDatetimeEl.value;
        if (!inputDatetime) {
            timestampValueSEl.textContent = '请选择日期时间';
            timestampValueMsEl.textContent = '请选择日期时间';
            return;
        }
        
        const timezone = dateTimezoneEl.value;
        
        try {
            // 使用moment-timezone处理时区
            const date = moment.tz(inputDatetime, timezone);
            const timestampMs = date.valueOf(); // 获取毫秒时间戳
            const timestampS = Math.floor(timestampMs / 1000); // 获取秒时间戳
            
            // 同时显示秒和毫秒时间戳
            timestampValueSEl.textContent = timestampS;
            timestampValueMsEl.textContent = timestampMs;
        } catch (error) {
            timestampValueSEl.textContent = '转换失败，请检查输入';
            timestampValueMsEl.textContent = '转换失败，请检查输入';
        }
    });
    
    // 设置当前日期时间为默认值
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    
    inputDatetimeEl.value = `${year}-${month}-${day}T${hours}:${minutes}`;
});